#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import re
import json
import requests
import datetime
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.dnspod.v20210323 import dnspod_client, models

def getip(ip_url1, ip_url2):
    try:
        req = requests.get(ip_url1, timeout=3)
        if req.status_code != requests.codes.ok:
            req = requests.get(ip_url2, timeout=3)
    except Exception as e:
        return None

    return re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", req.text)[0]

def describe_record(domain, subdomain, cred):
    try:
        httpProfile = HttpProfile()
        httpProfile.endpoint = "dnspod.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = dnspod_client.DnspodClient(cred, "", clientProfile)

        req = models.DescribeRecordListRequest()
        params = {
            "Domain": domain,
            "Subdomain": subdomain
        }
        req.from_json_string(json.dumps(params))

        resp = client.DescribeRecordList(req)
        return resp.to_json_string()

    except TencentCloudSDKException as err:
        print(err)

def modify_dynamic_dns(ipaddr, domain, params_dict, cred):
    try:
        httpProfile = HttpProfile()
        httpProfile.endpoint = "dnspod.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = dnspod_client.DnspodClient(cred, "", clientProfile)

        req = models.ModifyDynamicDNSRequest()
        params = {
            "Domain": domain,
            "SubDomain": params_dict['Name'],
            "RecordId": params_dict['RecordId'],
            "RecordLine": "默认",
            "Value": ipaddr
        }
        req.from_json_string(json.dumps(params))
        resp = client.ModifyDynamicDNS(req)
        info = "{0} [{2}.{1}] 记录更新为 {3} !!! ".format(now, domain, params_dict['Name'], ipaddr)
        print(info)

    except TencentCloudSDKException as err:
        print(err)

def main():
    parser = argparse.ArgumentParser(description='Tencent Cloud DDNS Script')
    parser.add_argument('--secret_id', required=True, help='Tencent Cloud Access Key ID')
    parser.add_argument('--secret_key', required=True, help='Tencent Cloud Access Key Secret')
    parser.add_argument('--host', required=True, help='Domain host')
    parser.add_argument('--ip_url1', required=True, help='Primary IP query URL (e.g., ipconfig.io)')
    parser.add_argument('--ip_url2', required=True, help='Secondary IP query URL (e.g., api64.ipify.org)')

    args = parser.parse_args()

    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    subdomain = args.host
    ip_url1 = args.ip_url1
    ip_url2 = args.ip_url2

    AK = args.secret_id
    AS = args.secret_key
    cred = credential.Credential(AK, AS)

    ipaddr = getip(ip_url1, ip_url2)
    if not ipaddr:
        print("Failed to get external IP address.")
        return

    domain = '.'.join(subdomain.split('.')[-2:])
    subdomain = subdomain.split('.')[0]

    ret = describe_record(domain, subdomain, cred)
    Record_dict = eval(ret.replace('null', '0'))['RecordList'][0]

    modify_dynamic_dns(ipaddr, domain, Record_dict, cred)

if __name__ == "__main__":
    main()
